package com.tanker.common.utils;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

public class FileUtil {
	
	public static String upload(MultipartFile f) {
		//String rootPath = Constants.configData.getUploadPath() + "/";
		String rootPath = "";
		String newFileName = "";
		Calendar cal = Calendar.getInstance();  
		int month = cal.get(Calendar.MONTH) + 1;  
		int year = cal.get(Calendar.YEAR);  
		try {

			String filePath=rootPath+year+month+"/";  
			File dir=new File(filePath);  
			if(!dir.isDirectory())  
				dir.mkdir();  
			     
			String fileOriginalName=f.getOriginalFilename();  
			newFileName=UUID.randomUUID()+fileOriginalName.substring(fileOriginalName.lastIndexOf("."));  
			File file=new File(filePath+newFileName);  
			   //文件写入磁盘  
			f.transferTo(file); 
		} catch(Exception e) {
			e.printStackTrace();
		}
		   //返回存储的相对路径+文件名称  
		return year+month+"/"+newFileName;  
	}
	
	public static void download(HttpServletResponse response, String filePath, String fileName) {
		
		OutputStream out = null; 
		try { 
			response.reset(); 
			response.setContentType("application/octet-stream; charset=utf-8"); 
			response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
			
			String path = "";
			File file = new File(path + File.separator +filePath);
			
			out = response.getOutputStream(); 
			out.write(FileUtils.readFileToByteArray(file)); 
			
			out.flush(); 
		} catch (IOException e) { 
			e.printStackTrace(); 
		} finally { 
			if (out != null) { 
				try { 
					out.close(); 
				} catch (IOException e) { 
					e.printStackTrace(); 
				} 
				
			} 
		}
	}
	
}
